package DAO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import bean.*;
import conn.ConnectDatabase;
import service.IUserDao;

import bean.Userbean;
/**
 * 用户接口操作实现类，实现用户相关的基本操作
 * @author Administrator
 *
 */
public class UserDaoImp implements IUserDao {

	PreparedStatement ps = null;
	/**
	 * 用户注册
	 */
	public boolean insert(Userbean u) {
		int n=0;
		String sql="insert into user(username,password) values(?,?)";
		try{
		ps=ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setString(1, u.getId());
		ps.setString(2, u.getPassword());
		
		n = ps.executeUpdate();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return n>0;
	}

	public boolean delete(Userbean u) {
		String sql="delete from user where id=?";
		int n = 0;
		try{
		ps=ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setString(1, u.getId());
		n=ps.executeUpdate();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return n>0;
	}

	public boolean update(Userbean u) {
		return false;
	}
	/**
	 * 用户登录
	 */
	public Userbean queryById(Userbean u) {
		Userbean user =null;
		String sql="select * from user where username=? and password=?";
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql);
		ps.setString(1,u.getId());
		ps.setString(2,u.getPassword());
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			user=new Userbean();
			user.setId(rs.getString("username"));
			user.setPassword(rs.getString("password"));
		}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return user;
	}

	public List<Userbean> queryUser() {
		StringBuffer sql= new StringBuffer("select * from user where 1 =1");
		List<Userbean> list = new ArrayList<Userbean>();
		try{
		ps = ConnectDatabase.getConnection().prepareStatement(sql.toString());
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			Userbean user = new Userbean();
			user.setId(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			list.add(user);
		
		}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
